<?php

namespace app\controller;

use app\BaseController;

use think\facade\Db;
use think\facade\View;

class Index extends BaseController
{
    protected $shopName;
    protected $userRealName;
    protected $month;
    protected $lastMonth;
    protected $nextMonth;
    protected $constColumn = 'id,invoice_id,portfolio_id,portfolio_name,invoice_date,from_date,to_date,total_amount';
    protected $type = ['SP','SB','SD'];
    protected function initialize()
    {
        if(empty(input('shopName'))){
            die('请传入shopName');
        }
        if(empty(input('userRealName'))){
            die('请传入userRealName');
        }
        if(empty(input('month'))){
            die('请传入month');
        }
        $this->shopName = input('shopName');
        $this->userRealName = input('userRealName');
        $currentMonth = input('month');
        $this->month = $currentMonth;
        $currentMonthStartTime = substr($currentMonth, 0, 4).'-'.substr($currentMonth, -2).'-01 00:00:00';
        $lastMonth = date('Ym', strtotime('-1 month', strtotime($currentMonthStartTime)));
        $nextMonth = date('Ym', strtotime('+1 month', strtotime($currentMonthStartTime)));
        $this->lastMonth = $lastMonth;
        $this->nextMonth = $nextMonth;

        parent::initialize(); // TODO: Change the autogenerated stub
    }


    public function index()
    {

        $shopName = $this->shopName;
        $userRealName = $this->userRealName;
        $month = $this->month;

        $data = [
            'userRealName'=>$userRealName,
            'shopName'=>$shopName
        ];
        // 获取店铺id
        $shopSql = "SELECT shop_id FROM pwinerp_shops where shop_name like '".$shopName."%';";
        $data['shopSql'] = $shopSql;

        //获取user_id
        $userSql = "SELECT id FROM pwinerp_users where realname like '".$userRealName."%';";
        $data['userSql'] = $userSql;

        $basePath = './price/'.$userRealName.'/'.$shopName.'/';
        //基础信息
        $baseInfoPath = $basePath.'base_info.txt';
        if(file_exists($baseInfoPath)){
            $data['baseInfo'] = json_decode(file_get_contents($baseInfoPath),true);
        }else{
            $data['baseInfo'] = [];
        }
        $baseInfo = $data['baseInfo'];
        $shopId = $baseInfo['shop_id']??0;
        $userId = $baseInfo['user_id']??0;
        // 获取花费sql
        $costSql = "select  ".$this->constColumn." from pwinerp_amazonads_invoices_portfolios where shop_id = ".$shopId." AND invoice_date like '".$month."%' AND is_tgb = 2 AND ad_userid = ".$userId." ORDER BY from_date asc;";
        $costSql = $costSql. "\r\nselect  ".$this->constColumn." from pwinerp_amazonads_invoices_portfolios where shop_id = ".$shopId." AND invoice_date like '".$month."%' AND is_tgb = 2 AND ad_userid = ".$userId." ORDER BY from_date asc;";
        $data['constSql'] = $costSql;

        //花费总额
        $data['total_amount'] = '';
        $data['constColumn'] = [];
        $data['before_month_amount'] = 0;
        $data['beforeList'] = [];
        $data['next_month_amount'] = 0;
        $data['nextList'] = [];
        $monthPath =  $basePath.$month.'/';
        $constPath = $monthPath.'current_pwinerp_amazonads_invoices_portfolios.txt';
        $nextConstPath = $monthPath.'next_pwinerp_amazonads_invoices_portfolios.txt';
        $invoiceDetailPath = $monthPath.'current_pwinerp_amazonads_invoices_detail.txt';
        $nextInvoiceDetailPath = $monthPath.'next_pwinerp_amazonads_invoices_detail.txt';
        $salesPath = $monthPath.'current_pwinerp_amazonads_datas.txt';
        $nextSalesPath = $monthPath.'next_pwinerp_amazonads_datas.txt';
        if(file_exists($constPath)){
            $constContent = file_get_contents($constPath);
            if(!empty($constContent)){
                $constArray = $this->contentToArray($constContent,$this->constColumn);
                //当月总额
                $data['total_amount'] = array_sum(array_column($constArray,'total_amount'));

                // from_date包含上个月的列表
                $beforeList = [];
                foreach($constArray as $value){
                    if(strpos($value['from_date'],$this->lastMonth) !== false){
                        $beforeList[] = $value;
                    }
                }
                $data['before_month_amount'] = 0;
                if(!empty($beforeList)){
                    $data['before_month_amount'] = array_sum(array_column($beforeList,'total_amount'));
                }
                $data['constColumn'] = explode(',',$this->constColumn);
                $data['beforeList'] = $beforeList;


                //跨下个月花费
                if(file_exists($nextConstPath)){
                    $constContent = file_get_contents($nextConstPath);
                    if(!empty($constContent)){
                        $constNestArray = $this->contentToArray($constContent,$this->constColumn);
                        $afterList = [];
                        foreach($constNestArray as $value){
                            if(strpos($value['from_date'],$this->month) !== false){
                                $afterList[] = $value;
                            }
                        }
                        $data['next_month_amount'] = 0;
                        if(!empty($afterList)){
                            $data['next_month_amount'] = array_sum(array_column($afterList,'total_amount'));
                        }
                        $data['nextList'] = $afterList;
                    }
                }

                //真实花费区间范围
                $constBetween = [
                    $data['total_amount'] - $data['before_month_amount'] - $data['next_month_amount'],
                    $data['total_amount'] + $data['before_month_amount'] + $data['next_month_amount'],
                ];
                $data['constBetween'] = implode('-',$constBetween);

                //销售额的计算
                //开票明细的sql语句
                $invoiceDetailColumn = 'invoice_id,portfolio_id,campaign_id';
                $invoicesDeatilSql = "select  ".$invoiceDetailColumn." from pwinerp_amazonads_invoices_detail where shop_id = ".$shopId." AND invoice_id in ('".implode("','",array_column($constArray,'invoice_id'))."') AND portfolio_id in ('".implode("','",array_column($constArray,'portfolio_id'))."');";
                $data['invoicesDeatilSql'] = $invoicesDeatilSql;
                if(file_exists($invoiceDetailPath)){
                    $invoiceDetailContent = file_get_contents($invoiceDetailPath);
                    $invoiceDetailArray = $this->contentToArray($invoiceDetailContent,$invoiceDetailColumn);
                    $campaignIdArr = array_column($invoiceDetailArray,'campaign_id');

                    //获取销售额
                    $salesColumn = 'campaignid,sales14d';
                    $salesMonth = substr($month, 0, 4).'-'.substr($month, -2);
                    $salesSql = "select ".$salesColumn." FROM pwinerp_amazonads_datas where date like '".$salesMonth."%' AND shop_id =".$shopId." AND sales14d > 0 AND campaignid in ('".implode("','",$campaignIdArr)."') ORDER BY update_at ASC;";
                    $data['salesSql'] = $salesSql;
                    if(file_exists($salesPath)){
                        $salesContent = file_get_contents($salesPath);
                        $salesArr = $this->contentToArray($salesContent,$salesColumn);
                        $data['sales_amount'] = array_sum(array_column($salesArr,'sales14d'));
                    }
                    if(!empty($afterList)){
                        $nextInvoicesDeatilSql = "select  ".$invoiceDetailColumn." from pwinerp_amazonads_invoices_detail where shop_id = ".$shopId." AND invoice_id in ('".implode("','",array_column($afterList,'invoice_id'))."') AND portfolio_id in ('".implode("','",array_column($afterList,'portfolio_id'))."');";
                        $data['invoicesNextDeatilSql'] = $nextInvoicesDeatilSql;
                        if(file_exists($nextInvoiceDetailPath)){
                            $nextInvoiceDetailContent = file_get_contents($nextInvoiceDetailPath);
                            $nextInvoiceDetailArray = $this->contentToArray($nextInvoiceDetailContent,$invoiceDetailColumn);
                            $nextCampaignIdArr = array_column($nextInvoiceDetailArray,'campaign_id');

                            // 获取下个月销售额
                            $salesMonth = substr($this->nextMonth, 0, 4).'-'.substr($this->nextMonth, -2);
                            $nextSalesSql = "select ".$salesColumn." FROM pwinerp_amazonads_datas where date like '".$salesMonth."%' AND shop_id =".$shopId." AND sales14d > 0 AND campaignid in ('".implode("','",$nextCampaignIdArr)."') ORDER BY update_at ASC;";
                            $data['nextSalesSql'] = $nextSalesSql;

                            if(file_exists($nextSalesPath)){
                                $salesContent = file_get_contents($nextSalesPath);
                                $salesNextArr = $this->contentToArray($salesContent,$salesColumn);
                                $data['next_sales_amount'] = array_sum(array_column($salesNextArr,'sales14d'));
                            }
                        }

                    }
                    if(!empty($constArray) && !empty($campaignIdArr) && !empty($salesArr)){
                        $res = $this->dissType($constArray,$invoiceDetailArray,$salesArr);
                        $data['current_sales_amount_diff'] = $res;
                    }
                    if(!empty($constNestArray) && !empty($nextCampaignIdArr) && !empty($salesNextArr)){
                        $res = $this->dissType($constNestArray,$nextInvoiceDetailArray,$salesNextArr);
                        $data['next_sales_amount_diff'] = $res;
                    }
                }
            }
            //当月的花费区分
            if(!empty($constArray)){
                $res = $this->dissTypeConst($constArray);
                $data['current_diff_const'] = $res;
            }
            //上月的花费区分
            if(!empty($beforeList)){
                $res = $this->dissTypeConst($beforeList);
                $data['before_current_diff_const'] = $res;
            }
            //下月的花费区分
            if(!empty($constNestArray)){
                $res = $this->dissTypeConst($constNestArray);
                $data['next_current_diff_const'] = $res;
            }

            //区分真实花费区间范围
            $betweenDiff = [];
            foreach($this->type as $t){
                $betweenDiff[$t] = [
                    ($data['current_diff_const'][$t]??0) - ($data['before_current_diff_const'][$t]??0) - ($data['next_current_diff_const'][$t]??0),
                    ($data['current_diff_const'][$t]??0) + ($data['before_current_diff_const'][$t]??0) + ($data['next_current_diff_const'][$t]??0)
                ];
            }
            foreach($betweenDiff as &$value){
                $value = implode('-',$value);
            }
            $data['betweenDiff'] = $betweenDiff;
        }
        $data['type'] = $this->type;
        return View::fetch('index',$data);

    }

    /**
     * content转为键值对数组
     * @param $content
     * @param $column
     * @return array
     */
    protected function contentToArray($content,$column){
        $constArray = [];
        $constArray1 = explode("\r\n",$content);
        foreach($constArray1 as $value){
            $bb = preg_replace("/\s/","$$$$",$value);
            $explodeArr = explode('$$$$',$bb);
            if(!empty($explodeArr)){
                $explodeKey = explode(',',$column);
                $row = [];
                foreach($explodeArr as $key=>$val){
                    $row[$explodeKey[$key]] = $val;
                }
                $constArray[] = $row;
            }
        }
        return $constArray;
    }

    protected function dissType($constArray,$invoiceDetailArray,$salesArr){
        $portfolio = [];
        foreach($constArray as $value){
            if(strpos($value['portfolio_name'],'-SB')){
                $portfolio[$value['portfolio_id']] = 'SB';
            }elseif(strpos($value['portfolio_name'],'-SD')){
                $portfolio[$value['portfolio_id']] = 'SD';
            }else{
                $portfolio[$value['portfolio_id']] = 'SP';
            }
        }
        $compainIdArr = [];
        foreach($invoiceDetailArray as $value){
            $compainIdArr[$portfolio[$value['portfolio_id']]][] = $value['campaign_id'];
        }

        $salesSpSdSb = [];
        foreach($salesArr as $value){
            foreach($compainIdArr as $k=>$v){
               if(in_array($value['campaignid'],$v)){
                   $salesSpSdSb[$k][] = $value;
               }
            }
        }
        $res = [];
        foreach($salesSpSdSb as $key=>$value){
            $res[$key]['sales_amount'] = array_sum(array_column($value,'sales14d'));
            $res[$key]['list'] = $value;
        }
        return $res;
    }

    /**
     * 花费做区分
     * @return void
     */
    public function dissTypeConst($constArray){
        $diffArr = [];
        foreach($constArray as $value){
            if(strpos($value['portfolio_name'],'-SB')){
                $diffArr['SB'][] = $value;
            }elseif(strpos($value['portfolio_name'],'-SD')){
                $diffArr['SD'][] = $value;
            }else{
                $diffArr['SP'][] = $value;
            }
        }
        $type = $this->type;
        $res = [];
        foreach($type as $t){
            $res[$t] = empty($diffArr[$t]) ? 0 : array_sum(array_column($diffArr[$t],'total_amount'));
        }
        return $res;
    }


}
